<?php

/**
 * User: htt
 * Date: 2019-02-20
 * Time: 上午10:54
 */

namespace App\Models\User;

use App\Jobs\Fun;
use App\Models\Admin\CompanyModel;
use App\Models\Admin\UserAccessModel;
use App\Models\AreaModel;
use App\Utilities\Utility;
use Illuminate\Support\Facades\Redis;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Cookie;
//class UserModel extends Authenticatable implements JWTSubject
class UserModel extends Authenticatable {

    use Notifiable;

    protected $table = 'users';
    protected $fillable = ['phone', 'password', 'username'];
    protected $hidden = ['password', 'remember_token'];
    protected $primaryKey = 'id';
    public $timestamps = false;


    /**
     * 新的主体类型 :101表示公司;102表示工厂;103表示个人应聘
     * 101表示公司
    */
    const type_gs=101;
    /**
     *102表示工厂
    */
    const type_gc=102;
    /**
     *103表示工厂
    */
    const type_gr=103;





    public function getJWTIdentifier() {
        return $this->getKey();
    }

    public function getJWTCustomClaims() {
        return [];
    }

    public function getCreateReloadNeedParams() {
        return [
            'phone', 'password', 'name', 'type'
        ];
    }

    const defaultHead = '/h5/images/toux01.png';

    /**
     * 功能状态 打开状态
     */
    const is_kaiguan_yes=1;
    /**
     * 功能状态 关闭状态
     */
    const is_kaiguan_no=0;


    /**
     *  获取用户信息
     */
    public static function getinfo($id) {
        if (strpos($id, 'mc_') !== false) {
            $find=self::where('jiguang_id', $id);
        } else{
            $find=self::where('id', $id);

        }


        $one = $find->select([
            'head','name','id','phone','sex',
            'is_company','is_factory','is_yingpin','jiguang_id'
        ])->first();
        if ($one) {
            $one=$one->toArray();
            $one['sex']=UserModel::sexTo($one['sex']);
            $one['head'] = \App\Jobs\Fun::pImg($one['head'] ? $one['head'] :Fun::$HOST. self::defaultHead);
            return $one;
        } else {
            return [
                'head' => Fun::$HOST.self::defaultHead,
                'name' => '未知用户',
                'id'=>null,
                'phone'=>'',
                'sex'=>'',
                'is_company'=>0,'is_factory'=>0,'is_yingpin'=>0
            ];
        }
    }
    /**
     * 如果是游客用户,直接返回true
    */
    public function isGuest(){

        return !$this->getId();
    }

    private $_model = null;
    /**
     * @return type UserModel
     */
    public function getModel($token = null) {
        if ($this->_model) {
            return $this->_model;
        }
          //  exit('sssssss');

        /// var_dump($token);exit;
        $modelAcc=$this->getUserIdRedis($token);
         if(!$modelAcc){
             return null;
         }
        $uid=$modelAcc;//$modelAcc->uid;

        $model= UserModel::where('id',$uid) 
                ->select(
                    'id',
                    'phone',
                    'name',
                    'money',
                    'type',
                    'head',
                    'jiguang_id',
                    'jiguang_pass',

                    'is_company',
                    'is_factory',
                    'is_yingpin'
                )
                ->first();
        
        
        if (!$model) {
            return null;
        }
        $this->_model = $model;///->toArray();
        return $this->_model;
    }

    /**
     * 获取缓存的用户数据
    */
    public function getCacheModel(){
        $key='user'.$this->getId();
        $cache=Redis::get($key);
        if($cache){
            return json_decode($cache,true);
        }
        $data=$this->getModel();
        Redis::setex($key,60*10,json_encode($data));
        return $data;
    }

    /**
     * 清除缓存
    */
    public function clearCacheModel($uid=null){
        if($uid===null){
            $uid=$this->getId();
        }
         $key='user'.$uid;
         Redis::del($key);
    }









    public function getToken(){
         $token=request()->cookie('token');

        ///var_dump($token);exit;
        if ($token) {
            return $token;
        } elseif (isset($_GET['token'])) {
            $token = $_GET['token'];
        }elseif(isset($_POST['token'])){
            $token=$_POST['token']??'';
        }else{
            $token='';
        }
        if($token==='不再使用'){
            return null;
        }
       // var_dump($token);exit;
        return $token;
    }
    private $UserAccess=false;
    private function getUserAccess($token){
        if($this->UserAccess){
           return $this->UserAccess;
        }

        if (!$token) {
            $token=$this->getToken();
        }
        if(!$token){
            return null;
        }
        $modelAcc = UserAccessModel::where('token', $token)
            ->select('uid')
            ->orderBy('id', 'desc')
            ->first();
        if(!$modelAcc){
            return null;
        }
        $this->UserAccess=$modelAcc;
        return $modelAcc;
    }
    private $UserId=false;
    private $RedisName='user';
    private $RedisTime=60*60*24*7;
    private function getUserIdRedis($token){
        if($this->UserId){
           return $this->UserId;
        }

        if (!$token) {
            $token=$this->getToken();
        }
        if(!$token){
            return null;
        }
        $exists=Redis::exists($this->RedisName.$token);
        if(!$exists){
            return null;
        }
        $id=Redis::get($this->RedisName.$token);

        if($id===null){
            return null;
        }

        Redis::expire($this->RedisName.$token,$this->RedisTime);
        return (int)$id;
    }

    /**
     * 记录用户状态
    */
    public function accessSet($uid){
        $token = Utility::getRandStr(rand(60,80));
        Redis::set($this->RedisName.$token,$uid);
         Redis::expire($this->RedisName.$token,$this->RedisTime);
         return $token;
       // var_dump($uid);exit;
    }


    public function getId($token = null) {
        $model = $this->getUserIdRedis($token);
        if ($model) {
            return $model ;
        } else {
            return 0;
        }
    }

    public function getMoney($token = null) {
        $model = $this->getModel($token);
        if ($model&&$model['money']) {
            return (float)$model['money'];
        } else {
            return 0;
        }
    }
    
    /***
     * 获取指定id的用户名
*/
    public static function idToName($id){
         $one = self::where('id', $id)->select('name')->first();
         if($one){
             return $one->name;
         }else{
             return '未知';
         }
    }
     
    public function getHead(){
        if($this->head){
            return \App\Jobs\Fun::pImg($this->head);
        }else{
            return Fun::$HOST .self::defaultHead;
        }
    }
    
    /**
     * 返回类型名称
     */
    public function getTypeName(){
        $UserRe=new \App\Repositories\Admin\UserRepository;
        $model=$this->getModel();
        return $UserRe->getTypeName($model);
    }

    /**
     * 男
     */
    const Sex_Nan='1';
    /**
     * 女
     */
    const Sex_Nv='2';

    /**
     * 性别
     * 性别：1男；2，女
    */
    public static function sexTo($val){
        if($val==self::Sex_Nan){
            return '男';
        }elseif($val==self::Sex_Nv){
            return '女';
        }elseif($val=='3'){
            return '不限';
        }else{
            return '未知';
        }
    }

    /**
     * 获取企业的资料
     * $tocity 表示是否转换为城市字符串
    */
    public function getComPanyVal($type,$uid=null,$tocity=false){
        if($uid===null){
            $uid=$this->getId();
        }
        $CompanyModel=null;
        if($type==CompanyModel::type_gongchang){
            $CompanyModel=UsergongchangModel::class ;
        }elseif($type==CompanyModel::type_gongsi){
            $CompanyModel=UserGongsiModel::class;
        }else{
            return null;
        }


        $val=$CompanyModel::where([
            'uid'=>$uid,
           // 'type'=>$type
        ])->select([
            'comCity','com_address','com_name','visible','shenhe','position'
        ])->first();


        if($val ){
            $val=$val->toArray();
          ///  $val['com_city_str']=AreaModel::getMergerName($val['com_city']);
            return $val;
        }else{
            return false;
        }
    }



    /**
     * 判断是否允许招聘
    */
    public function yunxuZhaopin(){
        $user=$this->getModel();
        if(($user['is_company']&&$user['is_company']!=0)||($user['is_factory']&&$user['is_factory']!=0)){
            return true;
        }else{
            return false;
        }
    }


}
